/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.juick.mod;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import org.json.JSONArray;

/**
 *
 * @author ugnich
 */
public class TagsActivity extends ListActivity implements OnItemClickListener {

    private ArrayAdapter<String> listAdapter;
    private View viewLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTitle(R.string.Popular_tags);

        viewLoading = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listitem_loading, null);
        viewLoading.setBackgroundColor(MainActivity.backgroundColor);
        
    	getListView().setCacheColorHint(0x00000000);
        getListView().addFooterView(viewLoading, null, false);

        listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        getListView().setAdapter(listAdapter);

        getListView().setOnItemClickListener(this);

        Thread thr = new Thread(new Runnable() {

            public void run() {
                final String jsonStr = MainActivity.getJSON(TagsActivity.this, "http://api.juick.com/tags");
                TagsActivity.this.runOnUiThread(new Runnable() {

                    public void run() {
                        if (jsonStr != null) {
                            try {
                                JSONArray json = new JSONArray(jsonStr);
                                int cnt = json.length();
                                for (int i = 0; i < cnt; i++) {
                                    listAdapter.add(json.getJSONObject(i).getString("tag"));
                                }
                            } catch (Exception e) {
                                Log.e("initTagsAdapter", e.toString());
                            }
                        }
                        TagsActivity.this.getListView().removeFooterView(viewLoading);
                    }
                });
            }
        });
        thr.start();
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent i = new Intent(this, MessagesActivity.class);
        i.putExtra("tag", listAdapter.getItem(position));
        startActivity(i);
    }
}
